package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.BaseException;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 距离计算工具类
 */
public class DistanceUtil {

    private final static String addressService = "https://api.map.baidu.com/geocoding/v3/";
    private final static String distanceService ="https://api.map.baidu.com/direction/v2/driving";

    //获取经纬度
    public static String originDestination(String response){
        JSONObject jsonResponse = JSON.parseObject(response);
        JSONObject result = jsonResponse.getJSONObject("result");
        JSONObject location = result.getJSONObject("location");
        BigDecimal lat = location.getBigDecimal("lat");
        BigDecimal lng = location.getBigDecimal("lng");
        return lat + ","+ lng ;
    }
    //计算距离
    public static Integer countDistance(Map<String, String> start, Map<String, String> end, String ak){
        //获取起点经纬度
        start.put("ak",ak);
        start.put("output","json");
        String response = HttpClientUtil.doGet(addressService, start);
        String startOriginDestination = originDestination(response);
        //获取终点经纬度
        end.put("ak",ak);
        end.put("output","json");
        String response2 = HttpClientUtil.doGet(addressService, end);
        String endOriginDestination = originDestination(response2);
        //通过进行路线规划计算距离
        Map<String, String> distanceDate = new HashMap<>();
        distanceDate.put("origin",startOriginDestination);
        distanceDate.put("destination",endOriginDestination);
        distanceDate.put("ak",ak);
        String distanceResponse = HttpClientUtil.doGet(distanceService, distanceDate);
        JSONObject jsonResponse = JSONObject.parseObject(distanceResponse);
        JSONObject result = jsonResponse.getJSONObject("result");
        JSONArray routes = result.getJSONArray("routes");
        JSONObject object = routes.getJSONObject(0);
        Integer distance = object.getInteger("distance");
        return distance;
    }


}
